//
//  RootViewManager.swift
//  EarbudsCommon
//
//  Created by 李然 on 2024/4/28.
//

import Foundation

/// 程序的根控制器管理器，其他模块不能随意控制根控制器
@objc public class RootViewManager: NSObject {
    private override init() {
        super.init()
    }

    @objc public static let `default` = RootViewManager()

    @objc public private(set) var rootViewController: UIViewController!

    private var lastViewController = UIViewController()

    @objc public var currentDisplayingViewController: UIViewController {
        return lastViewController
    }
}

extension RootViewManager {
    @objc public func constructRootView() {
        if rootViewController == nil {
            rootViewController = UIViewController()
            lastViewController.view.backgroundColor = .white
            rootViewController.view.addSubview(lastViewController.view)
            rootViewController.addChild(lastViewController)
        }
    }

    @objc public func transition(vc: UIViewController) {
        guard rootViewController != nil else {
            fatalError("请先调用 constructRootView!!!")
            return
        }

        dismissAll(vc: rootViewController, animated: false) {
            objc_sync_enter(self)

            self.rootViewController.addChild(vc)

            let toVC = vc
            let fromVC = self.lastViewController

            fromVC.willMove(toParent: nil)
            toVC.willMove(toParent: self.rootViewController)

            self.rootViewController.addChild(toVC)
            self.rootViewController.view.addSubview(toVC.view)

            fromVC.didMove(toParent: nil)
            toVC.didMove(toParent: self.rootViewController)
            self.lastViewController.removeFromParent()
            self.lastViewController.view.removeFromSuperview()
            self.lastViewController = vc
            objc_sync_exit(self)
        }
    }

    private func dismissAll(vc: UIViewController, animated: Bool, complete: @escaping () -> Void) {
        if vc.presentedViewController != nil {
            vc.dismiss(animated: animated) {
                self.dismissAll(vc: vc, animated: animated, complete: complete)
            }
        } else {
            complete()
        }
    }

    @objc public func getTopViewController() -> UIViewController {
        let window = UIApplication.shared.delegate!.window!!
        return _getTopViewControllerFrom(vc: window.rootViewController!)
    }

    private func _getTopViewControllerFrom(vc: UIViewController) -> UIViewController {
        if let next = vc.presentedViewController {
            return _getTopViewControllerFrom(vc: next)
        } else if let tab = vc as? UITabBarController, let selected = tab.selectedViewController {
            return _getTopViewControllerFrom(vc: selected)
        } else if let nav = vc as? UINavigationController, let last = nav.viewControllers.last {
            return _getTopViewControllerFrom(vc: last)
        }
        return vc
    }
}
